﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace XFramework
{

    /// <summary>
    /// 缓存池类
    /// </summary>
    public class Pool
    {
        //字典（该物体名，该物体列表）
        private Dictionary<string, List<GameObject>> objList;

        public Pool()
        {
            objList = new Dictionary<string, List<GameObject>>();
        }

        //拿取物体
        public GameObject Pop(string objName, Transform parent, Vector3 pos)
        {
            GameObject obj = null;
            if (objList.ContainsKey(objName) && objList[objName].Count > 0)
            {
                obj = objList[objName][0];
                obj.SetActive(true);
                obj.transform.parent = parent;
                objList[objName].Remove(obj);
            }
            else
            {
                GameObject prefab = Resources.Load<GameObject>("Prefab/" + objName);
                obj = GameObject.Instantiate(prefab, parent);
            }

            obj.name = objName;
            obj.transform.position = pos;
            return obj;
        }

        //回收物体
        public void Push(GameObject obj)
        {
            obj.SetActive(false);
            if (objList.ContainsKey(obj.name))
            {
                objList[obj.name].Add(obj);
            }
            else
            {
                objList.Add(obj.name, new List<GameObject>() { obj });
            }

        }

        //清空字典
        public void PoolClear()
        {
            objList.Clear();
        }
    }

}